package com.geekathon.mobzilla.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import com.geekathon.mobzilla.model.Bug;
import com.geekathon.mobzilla.model.BugHolder;
import com.geekathon.mobzilla.model.BugInfo;
import com.geekathon.mobzilla.model.Priority;
import com.geekathon.mobzilla.model.UserInfo;
import com.google.gson.Gson;

public class NetworkCallsUtil {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("error loading driver");
		}
	}

	private static final HashMap<String, UserInfo> userMap = new HashMap<String, UserInfo>();

	private static final HashMap<Integer, BugInfo> bugMap = new HashMap<Integer, BugInfo>();

	public static void pollBugzillaForUpdates() throws Exception {

		HttpClient client = new HttpClient();

		GetMethod getmethod = new GetMethod(
				"http://172.19.194.33:3000/bug?&include_fields=_all");

		client.executeMethod(getmethod);

		BufferedReader br = new BufferedReader(new InputStreamReader(
				getmethod.getResponseBodyAsStream()));
		String readLine;
		String temp = "";
		while (((readLine = br.readLine()) != null)) {
			System.err.println(readLine);
			temp = readLine;

		}

		System.out.println(temp);

		Gson gson = new Gson();
		BugHolder response = gson.fromJson(temp, BugHolder.class);
		List<Bug> bugList = response.getBugs();

		for (int i = 0; i < bugList.size(); i++) {
			Bug tempBug = bugList.get(i);
			UserInfo assignee = new UserInfo(tempBug.getAssignedTo().getName());
			userMap.put(tempBug.getAssignedTo().getName(), assignee);

			UserInfo creator = new UserInfo(tempBug.getCreator().getName());
			userMap.put(tempBug.getCreator().getName(), creator);

			BugInfo tempBugInfo = new BugInfo();
			tempBugInfo.setAssignedTo(tempBug.getAssignedTo().getName());
			tempBugInfo.setBugId(tempBug.getId());
			tempBugInfo.setComponent(tempBug.getComponent());
			tempBugInfo.setCreationTime(tempBug.getCreationTime());
			tempBugInfo.setCreator(tempBug.getCreator().getName());
			tempBugInfo.setLastChangeTime(tempBug.getLastChangeTime());
			tempBugInfo.setPriority(Priority.getEnumFormString(tempBug
					.getPriority()));
			tempBugInfo.setSeverity(Priority.getEnumFormString(tempBug
					.getSeverity()));
			tempBugInfo.setStatus(tempBug.getStatus());
			tempBugInfo.setProduct(tempBug.getProduct());

			bugMap.put(tempBugInfo.getBugId(), tempBugInfo);
			System.out.println(tempBugInfo);

		}

	}

	private static void executeJDBCCleanUp() throws Exception {
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:9129/test", "dba", "dba");

		PreparedStatement stmt = con.prepareStatement("delete from buginfo;");

		stmt.execute();
		stmt.close();
		con.close();
	}

	public static void main(String[] args) throws Exception {
		Timer t = new Timer();

		TimerTask task = new TimerTask() {
			public void run() {
				try {
					doIt();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};

		t.scheduleAtFixedRate(task, new Date(), 300000);
	}

	private static void doIt() throws Exception {
		executeJDBCCleanUp();
		pollBugzillaForUpdates();
		executeJDBCInsert();
	}

	private static void executeJDBCInsert() throws Exception {
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:9129/test", "dba", "dba");
		PreparedStatement stmt = con
				.prepareStatement("insert into buginfo values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		Collection<BugInfo> col = bugMap.values();

		Iterator<BugInfo> iterator = col.iterator();

		while (iterator.hasNext()) {
			BugInfo temp = iterator.next();
			System.out.println(temp.toString());
			stmt.setInt(1, temp.getBugId());
			stmt.setString(2, temp.getAssignedTo());
			stmt.setDate(3, new java.sql.Date(temp.getCreationTime().getTime()));
			stmt.setString(4, temp.getCreator());
			stmt.setString(5, temp.getStatus());
			stmt.setDate(6, new java.sql.Date(temp.getLastChangeTime()
					.getTime()));
			stmt.setInt(7, temp.getPriority());
			stmt.setInt(8, temp.getSeverity());
			stmt.setString(9, temp.getComponent());
			stmt.setString(10, temp.getProduct());

			stmt.execute();
		}

	}

}
